import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建 axios 实例
const request = axios.create({
  baseURL: 'http://127.0.0.1:8000',
  timeout: 10000
})

// 请求拦截器
request.interceptors.request.use(
  async (config) => {
    const token = localStorage.getItem('token')
    const tokenExpireTime = localStorage.getItem('tokenExpireTime')
    
    // 如果 token 在 5 分钟内过期，则刷新
    if (token && tokenExpireTime && Date.now() > tokenExpireTime - 5 * 60 * 1000) {
      const refreshToken = localStorage.getItem('refreshToken')
      try {
        const response = await axios.post('/users/refresh', { refresh_token: refreshToken })
        
        localStorage.setItem('token', response.data.token)
        localStorage.setItem('refreshToken', response.data.refresh_token)
        localStorage.setItem('tokenExpireTime', Date.now() + 30 * 60 * 1000)
        
        config.headers.Authorization = `Bearer ${response.data.token}`
      } catch (error) {
        // Refresh Token 失败，清除本地存储
        localStorage.clear()
        window.location.href = '/login'
      }
    } else if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    return response.data
  },
  async (error) => {
    if (error.response) {
      const { status, data } = error.response
      
      if (status === 401) {
        // Token 过期，尝试刷新
        const refreshToken = localStorage.getItem('refreshToken')
        if (refreshToken) {
          try {
            const response = await axios.post('http://127.0.0.1:8000/users/refresh', { 
              refresh_token: refreshToken 
            })
            
            localStorage.setItem('token', response.data.token)
            localStorage.setItem('refreshToken', response.data.refresh_token)
            localStorage.setItem('tokenExpireTime', Date.now() + 30 * 60 * 1000)
            
            // 重试原请求
            error.config.headers.Authorization = `Bearer ${response.data.token}`
            return request.request(error.config)
          } catch {
            // Refresh Token 也过期，跳转到登录页
            localStorage.clear()
            window.location.href = '/login'
            ElMessage.error('登录已过期，请重新登录')
          }
        } else {
          localStorage.clear()
          window.location.href = '/login'
          ElMessage.error('请先登录')
        }
      } else {
        ElMessage.error(data?.detail || '请求失败')
      }
    } else {
      ElMessage.error('网络错误，请检查您的网络连接')
    }
    
    return Promise.reject(error)
  }
)

export default request

